package fatecpg.com.br.japassei;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import fatecpg.com.br.japassei.bd.DisciplinaDAO;
import fatecpg.com.br.japassei.bd.Nota;
import fatecpg.com.br.japassei.prefs.Preferencias;

public class MainActivity extends Activity {
    Nota nota;
    Boolean editar;
    Boolean novo;
    int cdDisciplina;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Preferencias preferencias = new Preferencias(this);
        CheckBox chkSalvar = (CheckBox) findViewById(R.id.chkSalvarSair);

        try {
            chkSalvar.setChecked(preferencias.getSalvarDados());
        }catch (Exception ex){
            //Toast.makeText(getApplicationContext(), "Erro ao retornar preferências", Toast.LENGTH_SHORT).show();
        }

        Intent ver = getIntent();

        //if(ver.hasExtra("qt_prova1")){
        nota = new Nota(ver.getDoubleExtra("qt_prova1", 0), ver.getDoubleExtra("qt_prova2", 0), ver.getDoubleExtra("qt_traba", 0));
        this.cdDisciplina = ver.getIntExtra("cd_disciplina", 0);
        this.editar = ver.getBooleanExtra("ic_editar", true);
        this.novo = ver.getBooleanExtra("ic_novo", false);

        if(nota.getNota_p1()!=0) {
            ((EditText) findViewById(R.id.txtNotaP1)).setText(String.valueOf(nota.getNota_p1()));
        }
        if(nota.getNota_p2()!=0) {
            ((EditText) findViewById(R.id.txtNotaP2)).setText(String.valueOf(nota.getNota_p2()));
        }
        if(nota.getNota_tp()!=0) {
            ((EditText) findViewById(R.id.txtNotaTP)).setText(String.valueOf(nota.getNota_tp()));
        }
        //}

        ((EditText) findViewById(R.id.txtNotaP1)).requestFocus();
        ((EditText) findViewById(R.id.txtNotaP1)).setBackgroundColor(Color.parseColor("#C5F0C0"));
    }

    public EditText getSelectedEdit(){
        if(((EditText) findViewById(R.id.txtNotaP1)).isFocused()){
            return (EditText) findViewById(R.id.txtNotaP1);
        }else  if(((EditText) findViewById(R.id.txtNotaP2)).isFocused()){
            return (EditText) findViewById(R.id.txtNotaP2);
        }else  if(((EditText) findViewById(R.id.txtNotaTP)).isFocused()){
            return (EditText) findViewById(R.id.txtNotaTP);
        }else{
            return (EditText) findViewById(R.id.txtNotaP1);
        }
    }

    public void limpar(View view){
        getSelectedEdit().setText("");
        //EditText etNota1 = (EditText) findViewById(R.id.txtNotaP1);
        //EditText etNota2 = (EditText) findViewById(R.id.txtNotaP2);
        //EditText etTp = (EditText) findViewById(R.id.txtNotaTP);
        //etNota1.setText("");
        //etNota2.setText("");
        //etTp.setText("");
    }


    public void tabular(View view){
        EditText selecionado;
        if(((EditText) findViewById(R.id.txtNotaP1)).isFocused()){
            selecionado = (EditText) findViewById(R.id.txtNotaP2);
            ((EditText) findViewById(R.id.txtNotaP1)).setBackgroundColor(Color.WHITE);
            ((EditText) findViewById(R.id.txtNotaTP)).setBackgroundColor(Color.WHITE);
        }else  if(((EditText) findViewById(R.id.txtNotaP2)).isFocused()){
            selecionado = (EditText) findViewById(R.id.txtNotaTP);
            ((EditText) findViewById(R.id.txtNotaP2)).setBackgroundColor(Color.WHITE);
            ((EditText) findViewById(R.id.txtNotaP1)).setBackgroundColor(Color.WHITE);
        }else  if(((EditText) findViewById(R.id.txtNotaTP)).isFocused()){
            selecionado = (EditText) findViewById(R.id.txtNotaP1);
            ((EditText) findViewById(R.id.txtNotaP2)).setBackgroundColor(Color.WHITE);
            ((EditText) findViewById(R.id.txtNotaTP)).setBackgroundColor(Color.WHITE);
        }else{
            selecionado = (EditText) findViewById(R.id.txtNotaP1);
            ((EditText) findViewById(R.id.txtNotaP2)).setBackgroundColor(Color.WHITE);
            ((EditText) findViewById(R.id.txtNotaTP)).setBackgroundColor(Color.WHITE);
        }

        selecionado.setBackgroundColor(Color.parseColor("#C5F0C0"));
        selecionado.requestFocus();
    }

    public void salvar(View view){
        try {
            DisciplinaDAO disciplinaDAO = new DisciplinaDAO(this.getApplicationContext());
            if (disciplinaDAO.setNota(cdDisciplina, new Nota(getNotaP1(), getNotaP2(), getNotaTP()))) {
                Toast.makeText(getApplicationContext(), "Notas foram salvas", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Algum erro ocorreu", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(), "Erro ao salvar notas, " + ex.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public void configurar(View view){
        Intent config = new Intent(this, ConfigActivity.class);
        startActivity(config);
    }

    public void um(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "1");
    }
    public void dois(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "2");
    }
    public void tres(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "3");
    }
    public void quatro(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "4");
    }
    public void cinco(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "5");
    }
    public void seis(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "6");
    }
    public void sete(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "7");
    }
    public void oito(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "8");
    }
    public void nove(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "9");
    }
    public void zero(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + "0");
    }
    public void ponto(View view){
        getSelectedEdit().setText(getSelectedEdit().getText() + ".");
    }

    public String nvl(String texto){
        String valor;
        if(texto==null || texto.equals("")){
            valor ="0";
            return valor;
        }else{
            return texto;
        }
    }

    public void calcular(View view) {
        EditText tp = (EditText) findViewById(R.id.txtNotaTP);
        EditText p1 = (EditText) findViewById(R.id.txtNotaP1);
        EditText p2 = (EditText) findViewById(R.id.txtNotaP2);
        TextView res = (TextView) findViewById(R.id.txtResultado);


        if(Double.parseDouble(nvl(p1.getText().toString()))==0 && Double.parseDouble(nvl(p2.getText().toString()))!=0 &&  Double.parseDouble(nvl(tp.getText().toString()))==0){
            Toast.makeText(getApplicationContext(),"Não existe P2 sem P1",Toast.LENGTH_LONG).show();
        }else if (Double.parseDouble(nvl(p1.getText().toString()))>10 || Double.parseDouble(nvl(p2.getText().toString()))>10 || Double.parseDouble(nvl(tp.getText().toString()))>10){

            Toast.makeText(getApplicationContext(),"Valor fora do parâmetro",Toast.LENGTH_LONG).show();
          }else {
            if (!p1.getText().toString().equals("") && p2.getText().toString().equals("") && tp.getText().toString().equals("")) {
                Nota nota = new Matematica().notaComP1(Float.parseFloat(p1.getText().toString()));
                if (Double.parseDouble(String.valueOf(nota.getNota_tp())) <= 0) {
                    res.setBackgroundColor(Color.parseColor("#4DF23A"));
                    res.setText("Parabéns você já passou");
                    tp.setText("");
                    p2.setText("");
                } else {
                    p2.setText(String.valueOf(nota.getNota_p2()));
                    tp.setText(String.valueOf(nota.getNota_tp()));
                }
            } else if (!p1.getText().toString().equals("") && !p2.getText().toString().equals("") && tp.getText().toString().equals("")) {
                Nota nota = new Matematica().notaComP1P2(Float.parseFloat(p1.getText().toString()), Float.parseFloat(p2.getText().toString()));
                if (Double.parseDouble(String.valueOf(nota.getNota_tp())) > 10) {
                    res.setBackgroundColor(Color.parseColor("#F23A3A"));
                    res.setText("Infelizmente foi reprovado");
                    tp.setText("");
                } else if (Double.parseDouble(String.valueOf(nota.getNota_tp())) <= 0) {
                    res.setBackgroundColor(Color.parseColor("#4DF23A"));
                    res.setText("Parabéns você já passou");
                    tp.setText("");
                }
                tp.setText(String.valueOf(nota.getNota_tp()));
            } else if (!p1.getText().toString().equals("") && p2.getText().toString().equals("") && !tp.getText().toString().equals("")) {
                Nota nota = new Matematica().notaComP1TP(Float.parseFloat(p1.getText().toString()), Float.parseFloat(tp.getText().toString()));
                if (Double.parseDouble(String.valueOf(nota.getNota_p2())) > 10) {
                    res.setBackgroundColor(Color.parseColor("#F23A3A"));
                    res.setText("Infelizmente foi reprovado");
                    p2.setText("");
                } else if (Double.parseDouble(String.valueOf(nota.getNota_p2())) <= 0) {
                    res.setBackgroundColor(Color.parseColor("#4DF23A"));
                    res.setText("Parabéns você já passou");
                    p2.setText("");
                }
                p2.setText(String.valueOf(nota.getNota_p2()));
            } else if (p1.getText().toString().equals("") && p2.getText().toString().equals("") && !tp.getText().toString().equals("")) {
                Nota nota = new Matematica().notaComTP(Float.parseFloat(tp.getText().toString()));
                if (Double.parseDouble(String.valueOf(nota.getNota_p1())) <= 0) {
                    res.setBackgroundColor(Color.parseColor("#4DF23A"));
                    res.setText("Parabéns você já passou");
                    p1.setText("");
                    p2.setText("");
                } else {
                    p2.setText(String.valueOf(nota.getNota_p2()));
                    p1.setText(String.valueOf(nota.getNota_tp()));
                }

            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public void onPause(){
        super.onPause();

        Preferencias preferencias = new Preferencias(this);
        if(preferencias.getSalvarDados()) {
            try {
                DisciplinaDAO disciplinaDAO = new DisciplinaDAO(this.getApplicationContext());
                if (disciplinaDAO.setNota(cdDisciplina, new Nota(getNotaP1(), getNotaP2(), getNotaTP()))) {
                    Toast.makeText(getApplicationContext(), "Notas foram salvas", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Algum erro ocorreu", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception ex) {
                Toast.makeText(getApplicationContext(), "Erro ao salvar notas, " + ex.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    public float getNotaP1(){
        EditText p1 = (EditText) findViewById(R.id.txtNotaP1);
        String valor = p1.getText().toString();
        if(valor == null || valor.equals("")){
            return 0;
        }else{
            return Float.parseFloat(valor);
        }
    }

    public float getNotaTP(){
        EditText tp = (EditText) findViewById(R.id.txtNotaTP);
        String valor = tp.getText().toString();
        if(valor == null || valor.equals("")){
            return 0;
        }else{
            return Float.parseFloat(valor);
        }
    }

    public float getNotaP2(){
        EditText p2 = (EditText) findViewById(R.id.txtNotaP2);
        String valor = p2.getText().toString();
        if(valor == null || valor.equals("")){
            return 0;
        }else{
            return Float.parseFloat(valor);
        }
    }
}
